import { computed, ref } from 'vue';
import { defineStore } from 'pinia';
import { useUserStore } from '@/store';
import { addCartApi, userIdListApi } from '@/api/home/cart';
import type { CartVO } from '@/api/home/cart/types';

export const useCartStore = defineStore(
  'cart',
  () => {
    const userStore = useUserStore();
    const isLogin = computed(() => userStore.user.token);
    const cartList: any = ref([]);

    /*添加购物车*/
    const addCart = async (data: any) => {
      //是否登录
      if (isLogin.value) {
        //登录情况下调用后端接口
        console.log('已登录');
        //添加购物车
        await addCartApi(data);
        //获取购物车列表
        const res: any = await userIdListApi(userStore.user.userId, null);
        cartList.value = res.rows;
      } else {
        console.log('未登录');
        //未登录时，购物车信息保存到本地电脑
        // 确保 data 有 count 属性
        if (!data.count) {
          data.count = 1;
        }
        const item: any = cartList.value.find((item: any) => data.id === item.id);
        if (item) {
          item.count += data.count;
        } else {
          cartList.value.push(data);
        }
      }
    };
    /*计算属性-总数量(a:累加器,c:当前商品属性包括数量和价格，0:初始值)*/
    const totalCount = computed(() => cartList.value.reduce((a: number, c: any) => a + c.count, 0));
    /*计算属性-总价格(a:累加器,c:当前商品属性包括数量和价格，0:初始值)*/
    const totalMoney = computed(() => cartList.value.reduce((a: number, c: any) => a + c.count * c.price, 0));
    /*已选数量*/
    const selectedCount: any = computed(() => cartList.value.filter((item: any) => item.selected).reduce((a: number, c: any) => a + c.count, 0));
    /*已选合计金额*/
    const selectedMoney: any = computed(() => cartList.value.filter((item: any) => item.selected).reduce((a: number, c: any) => a + c.count * c.price, 0));
    /*是否全选*/
    const isAllCheck = computed(() => cartList.value.every((item: any) => item.selected));
    /*单选功能*/
    const singleCheck = (id: string, single: boolean) => {
      const item: any = cartList.value.find((item: any) => item.id === id);
      if (item) {
        item.selected = single;
      }
    };
    /*全选功能*/
    const allCheck = (selected: boolean) => {
      cartList.value.forEach((item: any) => (item.selected = selected));
    };

    /*删除商品*/
    const delCart = (skuId: number | string) => {
      //找到要删除的下标值
      const $index = cartList.value.findIndex((item: any) => skuId === item.id);
      cartList.value.splice($index, 1);
    };

    return {
      cartList,
      addCart,
      delCart,
      isAllCheck,
      totalCount,
      totalMoney,
      selectedCount,
      selectedMoney,
      singleCheck,
      allCheck
    };
  },
  {
    persist: true //同步到本地
  }
);
